package ooboo;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import twitter4j.Status;
import twitter4j.User;

public class ImageCache
{
	private static Hashtable<String,Image> images;
	private static String cachePath;
	private static final Image DEFAULT = new ImageIcon("images/default.png").getImage();
	
	static
	{
		images = new Hashtable<String,Image>();
		cachePath = Assets.getAppDataFolder().getAbsolutePath() + File.separator + "cache";
		
		File cache = new File(cachePath);
		
		if (!cache.exists())
			cache.mkdirs();
			
		//if(Assets.isFirstRun())
		//	new File(cachePath).mkdir();
	}
	
	public static Image getImage(String screenName)
	{
		Image image = images.get(screenName);
		if(image != null)
			return image;
		try
		{
			image = ImageIO.read(new File(cachePath + File.separator + screenName));
		}
		catch(IOException e){}
		if(image != null)
			return image;
		return DEFAULT;
	}
	
	public static void update(String screenName,URL url)
	{
		try
		{
			BufferedImage image = ImageIO.read(url);
			images.put(screenName,image);
			ImageIO.write(image,"png",new File(cachePath + File.separator + screenName));
		}
		catch(IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void update(List<Status> statues)
	{
		Set<String> checked = new HashSet<String>();
		
		for(Status status:statues)
		{
			User user = status.getUser();
			
			if(!checked.contains(user.getScreenName()))
			{
				checked.add(user.getScreenName());
				
				update(user.getScreenName(),user.getProfileImageURL());
			}
		}
	}
}
